package com.qf.openapi.web.master.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserSevice;
import com.qf.openapi.web.master.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/user")
@Slf4j   // 添加该注解后，可以使用 log对象进行日志的打印
public class UserController {

	@Autowired
	private UserSevice userSevice;


	/*
	* 登录验证
	* */
	@PostMapping("/login")
	public Result login(HttpServletRequest request,HttpServletResponse response, HttpSession session,String name,String password,String capchar,String checked ) {

		log.info( "接收的参数,name={},password={},capchar={}",name,password,capchar );

		//1. 处理验证码是否正确

		String cap=(String) session.getAttribute( "captcha" );
		if(!cap.equals( capchar )) {
			return new Result( ResultVo.UNSUCCESS,"验证码错误！！！" );
		}

		//2. 调用service层的方法进行登录验证
		User user=userSevice.login( name,password );
		log.info( "调用service层方法校验用户密码，返回的user对象={}",user );

		//3. 如果user不为null，则代表登录成功，如果user为null，则登录失败
		if(user!=null) {
			session.setAttribute( "user",user );
			if(checked.equals( "on" )){
				Cookie cookie=new Cookie( "name",name );
				Cookie cookie1=new Cookie( "password",password );
				cookie.setMaxAge( 7*24*60*60 );
				cookie1.setMaxAge( 7*24*60*60 );
				response.addCookie( cookie );
				response.addCookie( cookie1 );
			}
			return new Result( ResultVo.SUCCESS,"登录成功！！！" );

		}else {
			return new Result( ResultVo.UNSUCCESS,"登录失败！！！" );
		}

	};

	/*
	* 判断用户是否存在
	* */
	@PostMapping("/ifExi")
	public Integer login( String name ) {
		log.info( "接收的name,name={}",name );
		User user=userSevice.selectByName( name );
		//2. 调用service层的方法进行登录验证
		if(user!=null) {
			return 0;
		}
		return 1;
	}

    /*
    * 获取头像和用户名
    *  */
	@PostMapping("/toutou")
	public User login(HttpSession session  ) {
		User user=(User) session.getAttribute( "user" );
		return user;
	}


	/*hutool工具类
	* 返回验证码
	* */
	@RequestMapping("/getCaptcha")
	public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
		LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100,1,4);

		//将验证码放入session
		request.getSession().setAttribute("captcha", lineCaptcha.getCode());
		lineCaptcha.write(response.getOutputStream());
	}


	/*
	* 注册接口
	* */
	@PostMapping("/register")
	public Result register( HttpSession session,FormData formData ) throws IOException {

		log.info( "接收到的数据,${}",formData);
		String captcha=(String)session.getAttribute( "captcha" );
		if(!captcha.equals( formData.getCapchar() )){
			Result result=new Result( ResultVo.UNSUCCESS,"验证码错误" );
			return result;
		}

		String realPath=session.getServletContext( ).getRealPath( "/upload" );

		Integer register=userSevice.register( realPath,formData );
		if(register>0){
			return new Result( ResultVo.SUCCESS,"注册成功！！！" );
		}else {
			return new Result( ResultVo.UNSUCCESS,"数据库添加失败" );
		}
	}

	/*
	 * 页面添加接口
	 * */
	@PostMapping("/add")
	public Result add( HttpSession session,AddFormData addformData ) throws IOException {

		log.info( "接收到的数据,${}",addformData);

		String realPath=session.getServletContext( ).getRealPath( "/upload" );

		Integer register=userSevice.add( realPath,addformData );
		if(register>0){
			return new Result( ResultVo.SUCCESS,"添加成功！！！" );
		}else {
			return new Result( ResultVo.UNSUCCESS,"添加失败" );
		}
	}

	/*
	 * 页面添加接口
	 * */
	@PostMapping("/update")
	public Result update( HttpSession session,AddFormData addformData ) throws IOException {

		log.info( "接收到的数据,${}",addformData);

		String realPath=session.getServletContext( ).getRealPath( "/upload" );

		Integer register=userSevice.updateById( realPath,addformData );
		if(register>0){
			return new Result( ResultVo.SUCCESS,"Update Success" );
		}else {
			return new Result( ResultVo.UNSUCCESS,"Update UnSuccess" );
		}
	}
	/*hutool工具类
	 * 返回验证码
	 * */
	@GetMapping("/getUsers")
	public TableVo getUsers(Integer page,Integer limit) throws IOException {
		TableVo<User> tableVo=userSevice.getUsers(page,limit);
		log.info( "返回的数据,${}",tableVo );
		return tableVo;
	}

	/*
	 * 删除用户
	 * */
	@PostMapping("/del")
	public Result delUsers(int [] ids) throws IOException {
		log.info( "接收到的数据,arr=${}",ids );
		Result resultVo=userSevice.deleteUsers(ids);
		log.info( "删除成功！！！" );
		return resultVo;

	}
	/*
	* 返回cookie的接口
	* */
	@RequestMapping("/getCookie")
	public User getCookie(HttpServletRequest request) {
		Cookie[] cookies=request.getCookies( );
		String uname=null;
		String password=null;
		for(Cookie cookie: cookies) {
			if(cookie.getName( ).equals( "name" )) {
				uname=cookie.getValue( );
			}else
				if(cookie.getName( ).equals( "password" )) {
					password=cookie.getValue( );
				}
		}
		User user=userSevice.login( uname,password );
		if(user!=null){
			request.getSession().setAttribute( "user",user );
		}
		return user;
	}

	/*
	 * 注销用户
	 * */
	@RequestMapping("/deleteCookie")
	public Result deleteCookie(HttpServletRequest request,HttpServletResponse response) {
		//清空session的对象
		HttpSession session=request.getSession( );
		User user=(User) session.getAttribute( "user" );
		//删除数据库信息
		Integer integer=userSevice.deleteUserByName(user.getName());

		if(integer>0){
			session.invalidate();
			return  new Result( 0,"DELE SUCCESSFUL！！" );
		}else {
			return  new Result( 1,"DELE FAILE！！" );
		}
	}
	/*
	 * 搜索符合条件的用户
	 * */
	@RequestMapping("/getUsersByContdition")
	public TableVo<User> getUsersByContdition(Integer page,Integer limit,UserVo userVo) {
	log.info( "获取到的表单数据,data=${}",userVo,page,limit );

	TableVo<User> tableVo=userSevice.getUsersByContdition(page,limit,userVo);

	return tableVo;
	}

	@GetMapping("/export")
	public TableVo<String> export() throws IOException, IllegalAccessException, ClassNotFoundException {

		//1. 调用service层的方法进行数据导出，生成文件,返回文件名
		String filename=userSevice.export();

		log.info( "返回的文件名,name=${}",filename );
		List<String> list=new ArrayList<>(  );
		list.add( filename );
		//2. 返回包含文件名的 resultVO
		return new TableVo<String>(ResultVo.SUCCESS,"导出文件成功",list.size(),list);

	}
}
